package com.zone.vehicle.superApps.view;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.zone.lib.download.DownloadStatus;
import com.zone.lib.download.db.DownloadDaoUtilsStore;
import com.zone.lib.download.db.entity.Download;
import com.zone.vehicle.lib.view.VerticalTabLayout;
import com.zone.vehicle.superApps.databinding.ActivityMainBinding;
import com.zone.vehicle.superApps.view.adapter.AppFragmentPagerAdapter;
import com.zone.vehicle.superApps.view.adapter.TabAdapter;
import com.zone.vehicle.superApps.view.appmanager.AppManagerFragment;
import com.zone.vehicle.superApps.view.common.BackHandlerHelper;
import com.zone.vehicle.superApps.view.common.base.BaseActivity;
import com.zone.vehicle.superApps.view.home.HomeFragment;
import com.zone.vehicle.superApps.view.login.LoginActivity;
import com.zone.vehicle.superApps.view.login.message.LoginMessageFragment;
import com.zone.vehicle.superApps.view.receiver.SuperAppReceiver;
import com.zone.vehicle.superApps.view.setting.SettingActivity;
import com.zone.vehicle.superApps.view.setting.SuggestionFragment;
import com.zone.vehicle.superApps.view.setting.widget.CustomDialog;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;

import static com.zone.vehicle.lib.view.VerticalTabLayout.TAB_MODE_FIXED;

public class WelcomeActivity extends BaseActivity {

    private static final String TAG = WelcomeActivity.class.getSimpleName();

    private ActivityMainBinding binding;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        initViewPager();
        registerReceiver();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void setContentView() {
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
    }

    private void initViewPager(){
        binding.viewPager.setAdapter(new AppFragmentPagerAdapter(getSupportFragmentManager(), new ArrayList<>(getPagesMap().values())));
        binding.tabLayout.addOnTabSelectedListener(new MyOnTabSelectedListener());
        binding.tabLayout.setupWithViewPager(binding.viewPager, new TabAdapter(this, binding.tabLayout));
        binding.tabLayout.setTabMode(TAB_MODE_FIXED);

        binding.tabLayout.getTabAt(3).select();
    }

    @Override
    public void onBackPressed() {
        Log.d(TAG, "main onBackPressed ");
        if (!BackHandlerHelper.handleBackPress(this)) {
            super.onBackPressed();
        }
    }

    private void goLogin(){
        startActivity(new Intent(this, LoginActivity.class));
    }
    private void goSetting(){
        startActivity(new Intent(this, SettingActivity.class));
    }

    @Override
    public void initFragmentPages() {
        addPage(new LoginMessageFragment());
        addPage(new SuggestionFragment());//随便填一个占位
        addPage(new AppManagerFragment());
        addPage(new HomeFragment());
    }

    private class MyOnTabSelectedListener implements VerticalTabLayout.OnTabSelectedListener{

        @Override
        public boolean beforeSelect(VerticalTabLayout.VerticalTab newTab, VerticalTabLayout.VerticalTab currentTab) {

            if (newTab.getPosition() == 0){
                goLogin();
                return false;
            }
            if (newTab.getPosition() == 1){
                goSetting();
                return false;
            }
            Log.d(TAG, "tabLayout beforeSelect "+newTab.getText());
//                getSupportFragmentManager().beginTransaction().replace(R.id.body, tabFragments.get(newTab.getPosition())).commit();
            return true;
        }

        @Override
        public void onTabSelected(VerticalTabLayout.VerticalTab tab) {
        }

        @Override
        public void onTabUnselected(VerticalTabLayout.VerticalTab tab) {
        }

        @Override
        public void onTabReselected(VerticalTabLayout.VerticalTab tab) {
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "resume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "pause");
    }

    private void registerReceiver(){
        MyAppReceiver receiver = new MyAppReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(SuperAppReceiver.INSTALL_JINGDONG_ACTION);
        intentFilter.addAction(SuperAppReceiver.TEST_REMOTE_ACTION);
        registerReceiver(receiver, intentFilter);
    }

    private class MyAppReceiver extends BroadcastReceiver {
        public final String TAG = SuperAppReceiver.class.getName();

        public static final String INSTALL_JINGDONG_ACTION = "com.jingdong.manto.pkg.action";
        private static final String EVENT_DOWNLOADED = "downloaded";
        private static final String EVENT_DELETED = "deleted";
        public static final String TEST_REMOTE_ACTION = "com.superapp.showdialog";

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive:"+intent.getAction());
            Toast.makeText(context, "收到广播"+intent.getAction(), Toast.LENGTH_SHORT).show();
            String action = intent.getAction();
            if(TextUtils.equals(action, INSTALL_JINGDONG_ACTION)){
                String event = intent.getStringExtra("event");
                String appId = intent.getStringExtra("appId");
                String appType = intent.getStringExtra("appType");
                if (StringUtils.isNotEmpty(event) && event.equals(EVENT_DOWNLOADED)){
                    //小程序下载完成
                    Download download = new Download();
                    download.setCode(appId);
                    download.setType("2");
                    download.setSize(-1);
                    download.setDownloadLocation(-1);
                    download.setDownloadStatus(DownloadStatus.COMPLETE_INSTALL);
                    DownloadDaoUtilsStore.getInstance().getDownloadAppDaoUtils().insert(download);
                }else if (StringUtils.isNotEmpty(event) && event.equals(EVENT_DELETED)){
                    //小程序删除
                    DownloadDaoUtilsStore.getInstance().deleteByCode(appId);
                }
            }else if (TextUtils.equals(action, TEST_REMOTE_ACTION)){

                CustomDialog dialog = new CustomDialog(mContext);
                dialog.setTitle("远程请求安装APP，是否同意");
                dialog.setSubTitle("什么app");
                dialog.setPositive("同意");
                dialog.setNegtive("不同意");
                dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        dialog.cancel();
                    }
                });
                dialog.setOnClickBottomListener(new CustomDialog.OnClickBottomListener() {
                    @Override
                    public void onPositiveClick() {
                        Toast.makeText(context, "开始下载安装", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNegtiveClick() {
                        dialog.cancel();
                    }
                });
//                dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                dialog.show();
            }else if (TextUtils.equals(action, TEST_REMOTE_ACTION)){

            }

        }
    }

}